package com.evan.review.ipc;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Process;
import android.util.Log;

/**
 * 计数器服务
 * 使用自定义Binder实现跨进程通信
 */
public class CounterService extends Service {
    private static final String TAG = "CounterService";

    // 计数器值
    private int count = 0;

    /**
     * 自定义Binder类，提供计数器操作接口
     */
    public class CounterBinder extends Binder {
        
        // 获取当前计数
        public int getCount() {
            return count;
        }

        // 增加计数
        public void increment() {
            count++;
            Log.d(TAG, "计数增加到: " + count);
        }

        // 减少计数
        public void decrement() {
            count--;
            Log.d(TAG, "计数减少到: " + count);
        }

        // 重置计数
        public void resetCounter(int newValue) {
            count = newValue;
            Log.d(TAG, "计数重置为: " + count);
        }

        // 获取服务进程ID
        public int getServicePid() {
            return Process.myPid();
        }

        // 获取服务实例
        public CounterService getService() {
            return CounterService.this;
        }
    }

    // 创建Binder实例
    private final IBinder binder = new CounterBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "CounterService onCreate，进程ID: " + Process.myPid());
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "CounterService onBind");
        // 获取客户端传递的初始值
        if (intent != null && intent.hasExtra("initial_value")) {
            count = intent.getIntExtra("initial_value", 0);
            Log.d(TAG, "初始化计数器为: " + count);
        }
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "CounterService onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "CounterService onDestroy");
    }
} 